﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Controls;
using System.Collections;
using Components;
using Model;
using Model.Enum;
using Com.Seezt.Skins;
using UI.Lib;

namespace UI.ParentForm
{
    public partial class BaseForm : BasicForm
    {
        protected bool isDebug = false; //调试模式，是为了解决当期使用下，看不到编辑界面的bug

        private string winText;

        /// <summary>
        /// 当前行标题
        /// </summary>
        public string WinText
        {
            get { return winText; }
            set { winText = value; }
        }

        protected bool InitOk = true; //子页面中是否加载过程中出现了错误
        public bool IsInitOk
        {
            get { return InitOk; }
        }

        protected bool isLoadOk = false; //是否加载成功

        public BaseForm()
        {
            InitializeComponent();

            _pageInit();
        }

        private string _moduleCode;

        /// <summary>
        /// 模块名称
        /// </summary>
        public string ModuleCode
        {
            get { return _moduleCode; }
            set { _moduleCode = value; }
        }

        private string _action = "V";
        /// <summary>
        /// 当前功能代码
        /// </summary>
        public string Action
        {
            get { return _action; }
            set { _action = value; }
        }

        /// <summary>
        /// 添加默认事件
        /// </summary>
        protected void AddEvent(Control c)
        {
            if (c is PsPopWin) AddDefaultEvent(c as PsPopWin);
            else if (c is TextBox) AddDefaultEvent(c as TextBox);
            else if (c is PsDatePicker) AddDefaultEvent(c as PsDatePicker);
            else if (c is ComboBox) AddDefaultEvent(c as ComboBox);
        }

        /// <summary>
        /// 为TextBox添加默认的事件
        /// </summary>
        /// <param name="txt"></param>
        protected void AddDefaultEvent(TextBox txt)
        {
            if (txt == null) return;
            txt.KeyPress += new KeyPressEventHandler(Control_KeyPress);
        }

        /// <summary>
        /// 为PsDatePicker添加默认的事件
        /// </summary>
        /// <param name="dpc"></param>
        protected void AddDefaultEvent(PsDatePicker dpc)
        {
            if (dpc == null) return;
            dpc.KeyPress += new KeyPressEventHandler(Control_KeyPress);
        }

        /// <summary>
        /// 为ComboBox添加默认的事件
        /// </summary>
        /// <param name="cbx"></param>
        protected void AddDefaultEvent(ComboBox cbx)
        {
            if (cbx == null) return;
            cbx.KeyPress += new KeyPressEventHandler(Control_KeyPress);
        }

        private void _pageInit()
        {
            this.BackColor = Color.FromArgb(236, 241, 245);
        }

        /// <summary>
        /// 为PsPopWin添加默认的事件
        /// </summary>
        /// <param name="pop"></param>
        protected void AddDefaultEvent(PsPopWin pop)
        {
            if (pop == null) return;
            pop.TextChanged += new System.EventHandler(popwin_TextChanged);
            pop.Leave += new System.EventHandler(popwin_Leave);
            pop.KeyPress += new KeyPressEventHandler(popwin_KeyPress);
            pop.MouseDoubleClick += new MouseEventHandler(popwin_MouseDoubleClick);
            pop.KeyDown += new KeyEventHandler(pop_KeyDown);
        }

        #region 公用事件

        public void Control_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                Control c = sender as Control;
                if (null == c) return;

                if (AfterPressEnterOnSummary(c.Name))
                {
                    SendKeys.Send("{Tab}");
                    e.Handled = true; //不发出提示音
                }
            }
        }

        //当概要控件输入回车键时执行
        protected virtual bool AfterPressEnterOnSummary(string ctlName)
        {
            return true;
        }

        public void popwin_TextChanged(object sender, EventArgs e)
        {
            PsPopWin pop = sender as PsPopWin;
            if (pop == null || pop.IsUserModify == false) return;

            pop.IsValueChange = true;

            //string where = "";
            //bool flag = BeforePopWin(pop.Name, ref where);
            //if (!flag) return;

            //Hashtable hsWhere = null;
            //if (!string.IsNullOrEmpty(where))
            //{
            //    hsWhere = new Hashtable();
            //    hsWhere["strwhere"] = where;
            //}
        }

        public void popwin_Leave(object sender, EventArgs e)
        {
            PsPopWin pop = sender as PsPopWin;
            if (pop == null || pop.IsUserModify == false || pop.IsValueChange == false) return;

            pop.IsValueChange = false;

            string where = "";
            string[] others = null;
            bool flag = BeforePopWin(pop.Name, ref where, ref others);
            if (!flag) return;

            Hashtable hsWhere = new Hashtable(); ;
            if (!string.IsNullOrEmpty(where))
            {
                hsWhere["strwhere"] = where;
            }
            if (null != others && 0 != others.Length) //可能设置了其他条件
            {
                //条件设置的顺序分别如下 table | showfields | reffield 
                if (others.Length > 0 && null != others[0]) hsWhere["table"] = others[0];
                if (others.Length > 1 && null != others[1]) hsWhere["showfields"] = others[1];
                if (others.Length > 2 && null != others[2]) hsWhere["reffield"] = others[2];
            }

            pop.PressWord = pop.Text;
            PopService pservice = new PopService(pop.PopKey, hsWhere, pop.Text);
            Hashtable hs = pservice.GetSelectedData();

            pop.IsUserModify = false;

            bool isEmpty = string.IsNullOrEmpty(pop.Text);
            AfterSummaryPopUp(pop, hs, isEmpty, pservice.SearchState);
            AfterPopWin(pop.Name, hs, true);
            if ("M" == pservice.SearchState && !isEmpty)
            {
                popwin_MouseDoubleClick(sender, null);
            }
        }

        //概要弹出框后，执行
        protected virtual void AfterSummaryPopUp(PsPopWin popTarget, Hashtable hs, bool clearFlag, string status)
        {
            PopHelp.AfterPopWin(this.Controls, popTarget, hs, clearFlag, status);
        }

        public void popwin_KeyPress(object sender, KeyPressEventArgs e)
        {
            PsPopWin pop = sender as PsPopWin;
            if (pop == null) return;

            pop.IsUserModify = true;

            if (e.KeyChar == (char)13)
            {
                if (AfterPressEnterOnSummary(pop.Name))
                {
                    SendKeys.Send("{Tab}");
                    e.Handled = true; //不发出提示音
                }
            }
        }

        public void popwin_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            PsPopWin pop = sender as PsPopWin;
            if (pop == null) return;

            string pressWord = pop.PressWord;
            pop.PressWord = null;
            string o1 = pop.Text;
            string where = "";
            string[] others = null;
            bool flag = BeforePopWin(pop.Name, ref where, ref others);
            if (!flag) return;

            Hashtable hsWhere = new Hashtable();
            if (!string.IsNullOrEmpty(where))
            {
                hsWhere["strwhere"] = where;
            }
            if (null != others && 0 != others.Length) //可能设置了其他条件 zhuqiangwei 2011-02-09  加入
            {
                //条件设置的顺序分别如下 table | showfields | reffield 
                if (others.Length > 0 && null != others[0]) hsWhere["table"] = others[0];
                if (others.Length > 1 && null != others[1]) hsWhere["showfields"] = others[1];
                if (others.Length > 2 && null != others[2]) hsWhere["reffield"] = others[2];
            }

            FrmPopWin win = new FrmPopWin(pop.PopKey, hsWhere, pressWord);

            //计算弹出框的位置
            Point p = GetControlPosition(pop);
            win.Location = this.PointToScreen(new Point(p.X, p.Y + pop.Height));

            win.ShowDialog();
            if (win.IsSelected)
            {
                Hashtable hs = win.GetSelectedData();

                AfterSummaryPopUp(pop, hs, false, "S");

                pop.IsUserModify = false;

                AfterPopWin(pop.Name, hs, o1 != pop.Text);

                SendKeys.Send("{Tab}");
            }
        }

        protected void pop_KeyDown(object sender, KeyEventArgs e)
        {
            PsPopWin pop = sender as PsPopWin;
            if (pop == null) return;

            if (e.KeyCode == Keys.F1) //为弹出框添加F1开窗事件
            {
                popwin_MouseDoubleClick(sender, null);
                e.Handled = false;
            }
        }

        #endregion

        #region 虚拟方法

        public virtual bool BeforePopWin(string name, ref string where, ref string[] others)
        {
            where = "";
            others = null;
            return true;
        }

        public virtual void AfterPopWin(string name, Hashtable data, bool ischange)
        { }

        #endregion

        #region 操作符

        //根据字段的类型选择合适的操作符
        protected void GetOperateList(PsDataType dp, ToolStripComboBox cb)
        {
            if (null == cb) return;
            cb.Items.Clear(); //清空下框
            if (dp == PsDataType.Date || dp == PsDataType.Datetime) //日期
            {
                cb.Items.Add(new TextValuePair("等于", " datediff(d,{1},Convert(datetime,'{0}')) = 0 "));
                cb.Items.Add(new TextValuePair("早于", " {1} > CONVERT(datetime,'{0}')"));
                cb.Items.Add(new TextValuePair("晚于", " {1} < CONVERT(datetime,'{0}')"));
            }
            else if (dp == PsDataType.Num || dp == PsDataType.NumThanZero || dp == PsDataType.NumThanZeroOrEqualZero
                || dp == PsDataType.Int || dp == PsDataType.IntThanZero || dp == PsDataType.IntThanZeroOrEqualZero) //数字
            {
                cb.Items.Add(new TextValuePair("等于", " {1} = CONVERT(numeric(12,6), '{0}')"));
                cb.Items.Add(new TextValuePair("大于", " {1} > CONVERT(numeric(12,6), '{0}')"));
                cb.Items.Add(new TextValuePair("大于或等于", " {1} >= CONVERT(numeric(12,6), '{0}')"));
                cb.Items.Add(new TextValuePair("小于", " {1} < CONVERT(numeric(12,6), '{0}')"));
                cb.Items.Add(new TextValuePair("小于或等于", " {1} <= CONVERT(numeric(12,6), '{0}')"));
                cb.Items.Add(new TextValuePair("不等于", " {1} <> CONVERT(numeric(12,6), '{0}')"));
            }
            else //字符串等其他
            {
                cb.Items.Add(new TextValuePair("包含", " {1} LIKE '%{0}%' "));
                cb.Items.Add(new TextValuePair("不包含", " {1} NOT LIKE '%{0}%'  "));
                cb.Items.Add(new TextValuePair("等于", " {1} = '{0}' "));
                cb.Items.Add(new TextValuePair("以……开头", " {1} LIKE '{0}%' "));
                cb.Items.Add(new TextValuePair("以……结尾", " {1} LIKE '%{0}' "));
            }

            cb.Tag = dp;
            cb.SelectedIndex = 0; //让下拉框默认选中第一个
        }

        //检查操作符
        protected bool CheckOperate(PsDataType dp, string text)
        {
            if (string.IsNullOrEmpty(text)) return true;

            if (dp == PsDataType.Date || dp == PsDataType.Datetime)
            {
                if (!Validation.IsDate(text))
                {
                    MessageBox.Show("您输入的查询条件应该为日期格式。标准的格式是四位年-两位月-两位日。\n例如：2010-10-10 。", "提示");
                    return false;
                }
            }
            else if (dp == PsDataType.Num || dp == PsDataType.NumThanZero || dp == PsDataType.NumThanZeroOrEqualZero
                || dp == PsDataType.Int || dp == PsDataType.IntThanZero || dp == PsDataType.IntThanZeroOrEqualZero) //数字
            {
                if (!Validation.IsFloat(text))
                {
                    MessageBox.Show("您输入的查询条件应该为数字格式。\n\n输入的内容中不应该有字符、汉字或特殊符号。", "提示");
                    return false;
                }
            }

            return true;
        }

        #endregion

        public Size LstWindow
        {
            get { return new Size(600, 300); }
        }

        public Size MinWindow
        {
            get { return new Size(700, 400); }
        }

        public Size MidWindow
        {
            get { return new Size(800, 450); }
        }

        public Size MaxWindow
        {
            get { return new Size(850, 550); }
        }

        public Size LargeWindow
        {
            get { return new Size(950, 650); }
        }

        /// <summary>
        /// 用户设置Edit/Medit页面标题的样式,方便修改
        /// </summary>
        /// <param name="s1"></param>
        /// <param name="s2"></param>
        /// <returns></returns>
        protected string GetTitleStyle(string s1, string s2)
        {
            return string.Format("{0} | {1}", s1, s2);
        }

        #region 私有的辅助类

        private Point GetControlPosition(Control c)
        {
            int x = c.Location.X;
            int y = c.Location.Y;
            Control p = c.Parent;
            while (!(p is Form))
            {
                if (p == null)
                    break;
                x += p.Location.X;
                y += p.Location.Y;
                p = p.Parent;
            }

            return new Point(x, y);
        }

        #endregion

        /// <summary>
        /// 创建工具栏按钮
        /// </summary>
        /// <param name="key"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        protected ToolStripButton CreateToolBtn(string key, string text, EventHandler hder)
        {
            ToolStripButton btn = new ToolStripButton();
            btn.Name = "btn_" + key;
            btn.Tag = key;
            btn.Text = text;
            btn.DisplayStyle = ToolStripItemDisplayStyle.Text;
            btn.Click += hder;

            return btn;
        }

        /// <summary>
        /// 创建工具栏Checkbox
        /// </summary>
        /// <param name="key"></param>
        /// <param name="text"></param>
        /// <param name="isChecked"></param>
        /// <param name="box"></param>
        /// <returns></returns>
        protected ToolStripControlHost CreateToolCheckBox(string key, string text, bool isChecked, string toolTipText, EventHandler hder, out CheckBox box)
        {
            CheckBox tempBox = new CheckBox();
            tempBox.Checked = isChecked;
            tempBox.Name = key;
            tempBox.Text = text;
            tempBox.Click += hder;
            tempBox.BackColor = Color.Transparent;

            box = tempBox;
            ToolStripControlHost host = new ToolStripControlHost(tempBox);
            host.ToolTipText = string.IsNullOrEmpty(toolTipText) ? text : toolTipText;
            return host;
        }

        /// <summary>
        /// 工具栏上的按钮是否可以点击
        /// </summary>
        /// <param name="btn"></param>
        /// <returns></returns>
        protected bool CanClickButton(ToolStripButton btn)
        {
            if (null == btn || btn.Visible == false || btn.Enabled == false) return false;
            return true;
        }

        private void BaseForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape) //全局快捷键， Esc关闭窗口
            {
                this.Close();
            }
            else if (e.KeyCode == Keys.F12)
            {
                if (Context.IsSuperUser)
                {
                    MsgBox.Show(this.GetType().FullName);
                }
            }
        }


        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!string.IsNullOrEmpty(WinText))
            {
                //设置页面标题
                this.Text = this.winText;
            }

            isLoadOk = true;
        }
    }
}
